<template>
  <div>
    <!--  面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item> -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片视图区域 -->
    <el-card class="box-card">

      <!-- 栅格 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索框区域 -->
          <el-input placeholder="请输入内容"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getUsersList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary"
                     @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域
      :data="userList"绑定数据
      border边框
      stripe斑马纹
       -->
      <el-table :data="userList"
                border
                stripe
                style="width: 100%">
        <el-table-column type="index"
                         label="#"
                         width="40">
        </el-table-column>
        <el-table-column prop="username"
                         label="用户名称"
                         width="180">
        </el-table-column>
        <el-table-column prop="email"
                         label="邮箱"
                         width="180">
        </el-table-column>
        <el-table-column prop="mobile"
                         label="电话"
                         width="180">
        </el-table-column>
        <el-table-column prop="role_name"
                         label="角色"
                         width="180">
        </el-table-column>
        <el-table-column label="状态"
                         width="180">
          <!-- 作用域插槽的使用slot-scope -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
                       active-color="#409EFF"
                       inactive-color="#DCDFE6"
                       @change="userStateChanged(scope.row)">
            </el-switch>
          </template>

        </el-table-column>
        <!--  操作栏：删除，修改 -->
        <el-table-column label="操作"
                         width="180">
          <template slot-scope="scope">
            <!--  修改按钮 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="removeUserById(scope.row.id)"></el-button>
            <el-tooltip class="item"
                        effect="dark"
                        content="分配角色"
                        placement="top"
                        :enterable="false">
              <!-- 分配角色按钮 -->
              <el-button type="waring"
                         icon="el-icon-setting"
                         size="mini"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

      <!--  页码条区域
        handleSizeChange页面展示数据个数变化触发事件
        handleCurrentChange当前页码变化触发事件
         :current-page当前展示的页码
         :page-sizes 可供选择的更改页面数据个数数组
         :total总个数
       -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 2, 3, 4]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>

      <!-- 添加用户的对话框
      :visible.sync控制对话框打开与否
       -->
      <el-dialog title="请添加用户"
                 :visible.sync="addDialogVisible"
                 width="40%"
                 @close="addDialogClose">
        <!-- 添加用户表单区域 -->
        <el-form label-width="70px"
                 :model="addUsersForm"
                 :rules="addUsersFormRules"
                 ref="addFormRef">
          <!-- 用户名 -->
          <el-form-item prop="username"
                        label="用户：">
            <el-input v-model="addUsersForm.username"
                      prefix-icon="iconfont icon-user"></el-input>
          </el-form-item>
          <el-form-item prop="password"
                        label="密码：">
            <el-input v-model="addUsersForm.password"
                      prefix-icon="iconfont icon-user"></el-input>
          </el-form-item>
          <el-form-item prop="email"
                        label="邮箱：">
            <el-input v-model="addUsersForm.email"
                      prefix-icon="iconfont icon-user"></el-input>
          </el-form-item>
          <el-form-item prop="mobile"
                        label="电话：">
            <el-input v-model="addUsersForm.mobile"
                      prefix-icon="iconfont icon-user"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <!-- addUser添加用户表单的预先校验 -->
          <el-button type="primary"
                     @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户的对话框
      :visible.sync控制对话框打开与否
       -->
      <el-dialog title="修改用户"
                 :visible.sync="editDialogVisible"
                 width="40%"
                 @close="editDialogClose">
        <!-- 修改用户表单区域 -->
        <el-form label-width="70px"
                 :model="editForm"
                 :rules="editFormRules"
                 ref="editFormRef">
          <!-- 不可修改用户名
                注意：表单只读=disabled修饰表单项 -->
          <el-form-item prop="username"
                        label="用户：">
            <el-input v-model="editForm.username"
                      prefix-icon="iconfont icon-user"
                      disabled></el-input>
          </el-form-item>

          <el-form-item prop="email"
                        label="邮箱：">
            <el-input v-model="editForm.email"
                      prefix-icon="iconfont icon-user"></el-input>
          </el-form-item>
          <el-form-item prop="mobile"
                        label="电话：">
            <el-input v-model="editForm.mobile"
                      prefix-icon="iconfont icon-user"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <!-- addUser添加用户表单的预先校验 -->
          <el-button type="primary"
                     @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>
<script>
export default {
  data () {
    // 添加自定义的验证规则（电话号，邮箱）

    var checkEmail = (rule, value, callBack) => { // 验证邮箱
      var regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callBack()
      }
      callBack(new Error('请输入合法的邮箱'))
    }

    var checkMobile = (rule, value, callBack) => { // 验证电话
      var regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callBack()
      }
      callBack(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '', // 查询参数
        pagenum: 1, // 当前页码
        pagesize: 3 // 每页显示条数
      },
      userList: [], // 用户列表
      total: 0, // 用户总数
      // 添加用户对话框所需的数据属性
      addDialogVisible: false, // 添加用户对话框的打开与否
      // 添加用户表单数据数据绑定对象
      addUsersForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单数据校验规则
      addUsersFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改对话框数据对象
      editDialogVisible: false, // 修改用户对话框打开与否
      editForm: {},
      // 修改表单数据验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }

    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    // 获取用户列表事件
    async getUsersList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
      console.log(this.userList)
    },
    // 监听newSize变化
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    // 监听页码值变化
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUsersList()
    },
    // 监听switch开关状态，同步导数据后台  1.3.3. 修改用户状态
    async userStateChanged (userInfo) { // userInfo是一个形参，无实际意义
      console.log(userInfo)
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      // 注意：userInfo是一个jquery对象，想取其中某个固定属性的值，用${ userInfo.id } ，取id对应的属性值
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('用户状态更新失败!')
      }
      this.$message.success('用户状态更新成功!')
    },
    // 添加对话框关闭事件
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户的预校验
    addUser () {
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) return
        const { data: res } = await this.$http.post('users', this.addUsersForm)// 调用定义的添加用户数据的对象  接口：1.3.2. 添加用户
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        // 关闭添加用户的对话框
        this.addDialogVisible = false
        // 刷新用户列表
        this.getUsersList()
      })
    },

    // 修改用户对话框的展示
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取此用户id失败！')
      }
      this.editForm = res.data
      console.log(this.editForm)
      this.editDialogVisible = true
    },
    // 监听修改对话框关闭事件并重置表单
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改对话框关闭表单提交数据
    async editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (this.valid) { return }
        const { data: res } = await this.$http.put('users/' + this.editForm.id, { email: this.editForm.email, mobile: this.editForm.mobile })// 提交接口
        if (res.meta.status !== 200) { return this.$message.error('用户数据更新失败！') }
        // 关闭用户对话框
        this.editDialogVisible = false
        // 刷新用户列表
        this.getUsersList()
        this.$message.success('更新用户成功')
      })
    },

    // 删除按钮的弹窗事件removeUserById
    async removeUserById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // 用户点击确定 confirmResult接收confirm，点击取消confirmResult接收cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // 当用户点击确定时触发接口 1.3.6. 删除单个用户请求路径：
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getUsersList()
    }
  }
}
</script>
<style lang="less" scoped>
</style>
